package com.qd.moji;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 墨迹天气
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/sys/moji/")
@Slf4j
public class MojiController {
    private final ObjectMapper objectMapper;
    private final static String CITY_WEATHER_URL = "https://aliv18.mojicb.com/whapi/json/alicityweather/condition";
    private final static String WEATHER_URL = "https://aliv8.mojicb.com/whapi/json/aliweather/condition";
    private final static String AUTHORIZATION = "APPCODE e998833df3f84d379174376f4c798ffb";
    private final static String PREFIX_ID = "moji_cityId_{0}";
    private final RedisTemplateUtil<JsonNode> redisTemplateUtil;

    /**
     * 按城市ID获得天气
     *
     * @param cityId 天气
     * @return 天气信息
     */
    @GetMapping(value = "/cityWeather/condition")
    public ApiResultWrapper<Object> cityWeatherCondition(String cityId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, cityId);
        JsonNode jsonNode = redisTemplateUtil.get(new CacheKey().setTimeout(ConstantDto.REDIS_TIME_OUT_HOUR).setKey(key), () -> {
            Map<String, Object> params = new HashMap<>(1);
            params.put("cityId", cityId);
            try (HttpResponse response = HttpUtil.createPost(CITY_WEATHER_URL)
                    .header("Authorization", AUTHORIZATION).form(params).execute()) {
                String body = response.body();
                try {
                    return objectMapper.readTree(body);
                } catch (Exception e) {
                    log.error("获取天气信息失败: {}", response.body(), e);
                    throw new ApiException("获取天气信息失败");
                }
            }
        }, JsonNode.class);
        return ApiResult.success(jsonNode);
    }

    /**
     * 按金纬度获得天气信息
     *
     * @param lat 纬度
     * @param lng 经度
     * @return 天气信息
     */
    @GetMapping(value = "/weather/condition")
    public ApiResultWrapper<Object> weatherCondition(String lat, String lng) {
        Map<String, Object> params = new HashMap<>(1);
        params.put("lat", lat);
        params.put("lon", lng);
        try (HttpResponse response = HttpUtil.createPost(WEATHER_URL)
                .header("Authorization", AUTHORIZATION).form(params).execute()) {
            String body = response.body();
            try {
                return ApiResult.success(objectMapper.readTree(body));
            } catch (Exception e) {
                log.error("获取天气信息失败: {}", response.body(), e);
                throw new ApiException("获取天气信息失败");
            }
        }
    }
}
